import express from 'express'
import db from './db/index.js'
import userRouter from './route/user.js'
import questionRouter from './route/question.js'
import uploadRouter from './route/upload.js'
import router from './route/test.js'
import cors from 'cors'
import bodyParser from 'body-parser'
import { decrypt } from './libs/decrypt.js'
import { decode } from './interceptors/dehash.js'
import { tips } from './interceptors/tips.js'
import redis from './db/cache.js'
import { confirmSession } from './interceptors/user.js'
import answerRouter from './route/answer.js'
import { Server } from 'socket.io'
import { createServer } from 'http'
import moment from 'moment'
import chatRouter from './route/chat.js'
import { addChatMessage, queryChatHistory } from './service/chat.js'
import { queryUserById } from './service/user.js'

const app = express()
const chatServer = createServer(app)
const io = new Server(chatServer,{
  serveClient: false,
  cors: {
    origin: '*',
    methods: ['GET', 'POST'],
  },
})

redis.on("connect", function () {
    console.log("Redis client 已连接");
}).connect();

app.use(cors())
app.use( bodyParser.urlencoded({extended: true}) )
app.use( bodyParser.json())
app.use('/static', express.static('../assest'))
app.use(confirmSession)
app.use(tips)
app.use(uploadRouter)
app.use(decode)
app.use(userRouter)
app.use(questionRouter)
app.use(answerRouter)
app.use(chatRouter)
app.use(router)

io.on("connection", (socket) => {
  console.log('客户端连接')
  socket.on('refresh-message',async (data) =>{
    const chatHistory = (await queryChatHistory(data.sender_id, data.receiver_id)).reverse()
    
    let chatList = chatHistory.map((item)=>{
      return {
        sender_id: item.sender,
        receiver_id: item.receiver,
        message: item.message,
      }
    })
    socket.emit(`refresh-message-${data.sender_id}`, chatList);
  })
  socket.on('send-message', async (chatItem) => {
    const date = moment().format('YYYY-MM-DD HH:mm:ss');
    await addChatMessage(chatItem.sender_id, chatItem.receiver_id, chatItem.message, date)
    const chatHistory = (await queryChatHistory(chatItem.sender_id, chatItem.receiver_id)).reverse()
    let chatList = chatHistory.map(item=>{
      return {
        sender_id: item.sender,
        receiver_id: item.receiver,
        message: item.message,
      }
    })

    io.emit(`subscribe-${chatItem.receiver_id}`, chatItem.message);

    // 注意：向客户端推送消息要使用广播，而不是发送事件
    // socket.emit(`receive-message-${chatItem.receiver_id}`, chatList)
    io.emit(`receive-message-${chatItem.receiver_id}`,chatList)
    socket.emit(`refresh-message-${chatItem.sender_id}`,chatList)
  });
});

app.listen(3000, ()=>{
  console.log('3000端口正在运行...')
})

io.listen(3001, ()=>{
  console.log('3001端口正在运行...')
})